package fluebot;

import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import org.jibble.pircbot.User;

/**
 *
 * @author Aksel Kvitberg
 */
public class ChannelHandler {

	private HashMap<String, Log> logs = new HashMap<String, Log>();
	Fluebot controll;
	String channel;
	Random random = new Random();
	boolean silence = false;
	int hypnotoad = 0;

	public ChannelHandler(String channel, Fluebot controll) {
		this.controll = controll;
		this.channel = channel;
		controll.joinChannel(channel);
	}

	public void rejoin() {
		controll.joinChannel(channel);
	}

	public void dispose() {
	}

	public String getRandomUser() {
		User[] u = controll.getUsers(channel);
		return u[random.nextInt(u.length)].getNick();
	}

	public void onMessage(String sender, String login, String hostname, String message) {
		MessageHandler handler = new MessageHandler(sender, login, hostname, message);
		handler.start();
	}

	void onAction(String sender, String login, String hostname, String target, String action) {
	}

	private class MessageHandler extends Thread {

		private String sender;
		private String login;
		private String hostname;
		private String message;

		public MessageHandler(String sender, String login, String hostname, String message) {
			this.sender = sender;
			this.login = login;
			this.hostname = hostname;
			this.message = message;
		}

		public void run() {
			onMessage();
		}

		public void onMessage() {
			if (message.startsWith("!")) {
				String command = message.toLowerCase().split(" ")[0].substring(1);
//				System.out.println(command);

				switch (Commands.toCommand(command)) {
					case seen:
						seen(message);
						break;
					case timer:
						timer(sender, message);
						break;
					case addNote:
						addNote(sender, message);
						break;
					case addtotopic:
						addToTopic(sender, message);
						break;
					case bash:
						bash(message);
						break;
					case chuck:
						chuckNoris(message);
						break;
					case compliment:
						compliment(sender, message);
						break;
					case insult:
						insult(sender, message);
						break;
					case convert:
						unitConversion(message);
						break;
					case define:
						define(message);
						break;
					case face:
						faces(message);
						break;
					case fml:
						fml(message);
						break;
					case g:
						googleSearch(message);
						break;
					case imdb:
						imdb(message);
						break;
					case lastfm:
						lastFM(sender, message);
						break;
					case spell:
						spelling(message);
						break;
					case stats:
						stats(message);
						break;
					case hypnotoad:
						hypnotoad(message);
						break;
					case ud:
						urbanDirectory(message);
						break;
					case weather:
						weather(message);
						break;
					case whois:
						whois(sender, message);
						break;
					case roll:
						dice(sender, message);
						break;
					case attack:
						attack(sender, message);
						break;
					case exit:
						exit(sender, message);
						break;
					case join:
						join(sender, message);
						break;
					case leave:
						leave(sender, message);
						break;
					case silence:
						silence(sender, message);
						break;
					case add:
						addChannel(sender, message);
						break;
					case help:
						sendHelpMessage(channel);
						break;
					default:
						break;
				}
			}
// <editor-fold defaultstate="collapsed" desc="old code">
//		if (message.startsWith("!") && false) {
//			seen(message);
//			timer(sender, message);
//			addToTopic(sender, message);
//			addNote(sender, message);
//			moderate(sender, message);
//			stats(message);
//			whois(sender, message);
//
//			//Fun - Non internet
//			dice(sender, message);
//			attack(sender, message);
//			compliment(sender, message);
//			eightBall(sender, message);
//			faces(message);
//			paperscissorGame(sender, message);
//			unitConversion(message);
//
//			//Fun - internet
//			googleSearch(message);
//			chuckNoris(message);
//			define(message);
//			bash(message);
//			fml(message);
//			weather(message);
//			imdb(message);
//			lastFM(sender, message);
//			spelling(message);
//			urbanDirectory(message);
//		}// </editor-fold>
			// Div things that doesn't start with !
			youtube(message);
			logMessage(sender, login, hostname, message);
		}

		public void onAction(String sender, String login, String hostname, String target, String action) {
			logAction(sender, login, hostname, target, action);
		}

		private void logMessage(String sender, String login, String hostname, String message) {
			LogItem item = new LogItem();
			item.date = System.currentTimeMillis();
			item.time = getTime();
			item.hostname = hostname;
			item.login = login;
			item.nick = sender;
			item.message = message;
		}

		private void logAction(String sender, String login, String hostname, String target, String action) {
			LogItem item = new LogItem();
			item.date = System.currentTimeMillis();
			item.time = getTime();
			item.hostname = hostname;
			item.login = login;
			item.nick = sender;
			item.action = action;
		}

		private void seen(String message) {
//		Matcher seenMatcher = seenPattern.matcher(message);
//		if (seenMatcher.find()) {
//
//			String nick = seenMatcher.group(1);
//
//			Log log = logs.get(channel);
//			LogItem seen = log.lastSeen.get(nick.toLowerCase());
//
//			if (seen != null) {
//				sendMessage("User " + seen.nick + " was last seen on" + seen.getTime() + " " + seen.getLastEvent());
//			} else {
//				sendMessage("I haven't seen " + nick + " on this channel (yet)");
//			}
//		}
		}

		private void timer(String sender, String message) {
		}

		private void addToTopic(String sender, String message) {
		}

		private void addNote(String sender, String message) {
		}

		private void stats(String message) {
		}

		private void whois(String sender, String message) {
		}

		private void dice(String sender, String message) {
			int sides = 6;
			if (message.toLowerCase().startsWith("!roll")) {
				String[] tokens = message.split(" ");
				if (tokens.length > 1) {
					try {
						sides = Integer.parseInt(tokens[1]);
					} catch (Exception e) {
					}
				}
				int result = random.nextInt(sides);
				sendMessage(sender + " rolled a " + (result + 1));
			}
		}
		Attack attack = new Attack();

		private void attack(String sender, String message) {
			String[] tokens = message.split(" ");
			if (tokens.length > 1) {
				String target = tokens[1];
				if (random.nextDouble() > 0.95 || target.toLowerCase().equals("me")) {
					target = sender;
				}
				if (isInChannel(target)) {
					String send = attack.attack(target);
					if (send != null) {
						sendAction(send);
					}
				}
			}
		}

		private void compliment(String sender, String message) {
			String[] tokens = message.split(" ");
			String target = sender;
			if (tokens.length > 1) {
				target = tokens[1];
				if (target.equalsIgnoreCase("me")) {
					target = sender;
				}

			}
			if (isInChannel(target)) {
				String compliment = new Compliment().compliment(target, sender);
				sendMessage(compliment);
			}
		}
		
		private void insult(String sender, String message) {
			String[] tokens = message.split(" ");
			String target = sender;
			if (tokens.length > 1) {
				if (!tokens[1].equals("me")) {
					target = tokens[1];
				}
			}
			Insult insult = new Insult();
			String ins = insult.insult(target);
			sendMessage(ins);
		}

		private void eightBall(String sender, String message) {
		}

		private void faces(String message) {
		}

		private void paperscissorGame(String sender, String message) {
		}

		private void rpsGame(String sender, String message) {
		}

		private void unitConversion(String message) {
		}

		private void googleSearch(String message) {
		}

		private void chuckNoris(String message) {
		}

		private void define(String message) {
		}

		private void bash(String message) {
			String bash = Bash.getMessage();
			if (bash != null) {
				sendMessage(bash);
			}
		}

		private void fml(String message) {
		}

		private void weather(String message) {
		}

		private void imdb(String message) {
		}

		private void lastFM(String sender, String message) {
		}

		private void spelling(String message) {
		}

		private void urbanDirectory(String message) {
		}

		private void youtube(String message) {
		}

		private void sendMessage(String message) {
			if (!silence) {
				if (hypnotoad > 0) {
					message = message.substring(0, message.length() - (message.length() / 4)) + "-ALL GLORY TO THE HYPNOTOAD";
					hypnotoad--;
				}
				controll.sendMessage(channel, message);
			}
		}

		private void sendAction(String action) {
			if (hypnotoad > 0) {
				action = action.substring(0, action.length() - (action.length() / 4)) + "-ALL GLORY TO THE HYPNOTOAD";
				hypnotoad--;
			}
			controll.sendAction(channel, action);
		}
		private SimpleDateFormat shortDateFormat = new SimpleDateFormat("H:mm");
		private FieldPosition fp = new FieldPosition(0);

		public String getTime() {
			Date now = new Date();
			StringBuffer output = new StringBuffer();
			try {
				shortDateFormat.format(now, output, fp);
			} catch (NullPointerException e) {
				// Date cannot be null. Ignore this.
			}
			return output.toString();
		}

		boolean isInChannel(String nick) {
			for (User user : controll.getUsers(channel)) {
				System.out.println(user.getNick());
				if (user.equals(nick) || user.equals("%" + nick)) {
					System.out.println("Nick " + nick + " is in channel " + channel);
					return true;
				}
			}
			System.out.println("Nick " + nick + " is not in channel " + channel);
			return false;
		}

		private void exit(String sender, String message) {
			if (sender.equals("Flueworks")) // Change this!
			{
				System.exit(0);
			}
		}

		private void join(String sender, String message) {
			if (sender.equals("Flueworks")) { // Change this!
				String[] tokens = message.split(" ");
				if (tokens.length > 1) {
					controll.joinNewChannel(tokens[1]); // CHANGE!!!
				}
			}
		}

		private void leave(String sender, String message) {
			if (sender.equals("Flueworks")) { // Change this!
				String[] tokens = message.split(" ");
				if (tokens.length > 1) {
					controll.leaveChannel(tokens[1]);
				} else {
					controll.leaveChannel(channel);
				}
			}
		}

		private void silence(String sender, String message) {
			if (sender.equals("Flueworks")) { // Change this
				silence = !silence;
			}
		}

		private void addChannel(String sender, String message) {
			if (sender.equals("Flueworks")) {
				String[] tokens = message.split(" ");
				if (tokens.length > 1) {
					controll.addNewChannel(tokens[1]);
				}
			}
		}

		public void dispose() {
			// Do all log saving here before the object is disposed of.
		}

		private void sendHelpMessage(String channel) {
			sendMessage("FlueBot v." + controll.getVersion());
			sendMessage("Commands: !roll <sides>, !attack <user>, !compliment <user>, !insult <user> !bash");
		}


		private void hypnotoad(String message) {
			if (sender.equals("Flueworks")) { // Change this!
				String[] tokens = message.split(" ");
				if (tokens.length > 1) {
					try {
						System.out.println(tokens[1]);
						hypnotoad = Integer.parseInt(tokens[1]);
					} catch (Exception e) {
						System.err.println("Hypnotoad error");
					}
				} else {
					hypnotoad = 5;
				}
			}
		}
	}
}
